package monitor

import (
	"log"
	"net/http"

	"gitea.1216.top/lxy/zhub/internal/zbus"
	"github.com/gin-gonic/gin"
)

var r = gin.Default()

// Version 时间格式化 YYYY.MM.DD-HH.MM.SS
var Version string

func init() {
	// 1.日志文件 定期分割归档

}

func StartWatch() {

	r.GET("/", func(c *gin.Context) {
		c.File("./public/index.html")
	})

	r.GET("/_/info", func(c *gin.Context) {
		c.JSON(http.StatusOK, zbus.Info())
	})
	r.GET("/_/cleanup", func(c *gin.Context) {
		zbus.Bus.Clearup()
		c.JSON(http.StatusOK, "+OK")
	})
	r.GET("/_/version", func(c *gin.Context) {
		c.JSON(http.StatusOK, map[string]string{
			"version": Version,
		})
	})

	r.GET("/timer/reload", func(c *gin.Context) {
		zbus.Bus.ReloadTimer()
		c.JSON(http.StatusOK, "+reload timer ok")
	})
	r.POST("/message/send", func(c *gin.Context) {
		topic := c.PostForm("name")  // c.Query("topic")
		value := c.PostForm("value") // c.Query("value")
		// _type := c.PostForm("type")  // publish、broadcast

		log.Println(c.PostForm("type"), topic, value)
		switch c.PostForm("type") {
		case "broadcast":
			zbus.Bus.Broadcast(topic, value)
		case "publish":
			zbus.Bus.Publish(topic, value)
		default:

		}
		c.JSON(http.StatusOK, "+OK")
	})
	r.GET("/topic/delay", func(c *gin.Context) {
		topic := c.Query("topic")
		value := c.Query("value")
		delay := c.Query("delay")

		zbus.Bus.Delay([]string{"delay", topic, value, delay})
		c.JSON(http.StatusOK, "+OK")
	})

	// reload the auth configuration
	r.GET("/auth/reload", func(c *gin.Context) {
		zbus.AuthManager.Reload()
		c.JSON(http.StatusOK, "+OK")
	})

	watchAddr := zbus.Conf.Service.Watch
	r.Run(watchAddr)
}
